package com.briup.es.service.impl;

import com.briup.es.config.auth.SecurityUserContext;
import com.briup.es.config.exception.ServiceException;
import com.briup.es.config.response.ResultCode;
import com.briup.es.domain.bean.Shopcar;
import com.briup.es.domain.vo.BookDetailVO;
import com.briup.es.domain.vo.ShopCarGoodsVO;
import com.briup.es.mapper.ShopCarMapper;
import com.briup.es.service.BookService;
import com.briup.es.service.ShopCarService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;


@Service
@RequiredArgsConstructor
public class ShopCarServiceImpl implements ShopCarService {

    private final ShopCarMapper shopCarMapper;
    private final BookService bookService;

    @Override
    public List<ShopCarGoodsVO> queryList(Integer userId) {
        return shopCarMapper.queryByUserId(userId);
    }

    @Override
    public void addShopCar(Integer bookId) {
        // 确保该bookId对应的图书存在于数据库中
        BookDetailVO detailVO = bookService.queryBookDetailById(bookId);
        if (detailVO == null) {
            // 图书不存在，直接抛出异常
            throw new ServiceException(ResultCode.BOOK_IS_NOT_EXISTS);
        }

        if (detailVO.getStoreNum() == 0) {
            throw new ServiceException(ResultCode.BOOK_STORE_NUM_IS_NULL);
        }

        // 将图书id，图书数量，以及用户id添加到购物车表中
        Integer userId = SecurityUserContext.userId();
        // 根据用户id以及图书id，查询购物车中是否以及存在该图书，如果存在，那么修改数据，如果不存在，那么新增数据
        Shopcar shopcar = shopCarMapper.queryByUserIdWithBookId(userId, bookId);
        if (shopcar == null) {
            // 在当前用户的购物车不存在该图书，那么新增即可
            shopcar = new Shopcar();
            shopcar.setBookId(bookId);
            shopcar.setUserId(userId);
            shopcar.setNum(1);
            // 新增数据
            shopCarMapper.addShopcar(shopcar);
        } else {
            // 说明当前用户的购物车中存在该图书，那么需要修改购物车中图书商品的数量
            shopcar.setNum(shopcar.getNum() + 1);
            shopCarMapper.updateShopcar(shopcar);
        }
    }

    @Override
    public void updateShopcar(Integer id, Integer num) {
        // 根据购物车项id查询该购物车项，并且确保该购物车项还存在
        Shopcar shopcar = shopCarMapper.queryById(id);
        if (shopcar == null) {
            throw new ServiceException(ResultCode.PARAMS_IS_INVALID);
        }
        // 修改数量
        shopcar.setNum(num);
        shopCarMapper.updateShopcar(shopcar);
    }

    @Override
    public void deleteShopcar(List<Integer> ids) {
        if (CollectionUtils.isEmpty(ids)){
            return;
        }
        // 继续删除
        shopCarMapper.batchDelete(ids);
    }
}
